package gui;

import db.DB;
import dbVSguiConnection.GuiCallDb;
import dbVSguiConnection.GuiGetReturnedResults;
import details.Artist;
import details.Cd;
import details.Song;
import details.User;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuAdapter;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

public class Main extends Composite {
	private static Shell shell;
	private static Display display;
	private static int central_x;
	private static int central_y;
	static Menu menuBar;
	static Menu fileMenu;
	static Menu helpMenu;
	static MenuItem fileMenuHeader;
	static MenuItem helpMenuHeader;
	static MenuItem fileExitItem;
	static MenuItem fileSaveItem;
	static MenuItem helpGetHelpItem;
	private static Button searchDialogButtonSearchAlbum;
	private static Button searchDialogButtonSearchArtist;
	private static Button searchDialogButtonSearchSong;
	private static Group searchDialogGroup;
	private static Text searchDialogAlbumTitleText;
	private static Text searchDialogAlbumPerformerText;
	private static Text searchDialogAlbumGenreText;
	private static Text searchDialogAlbumYearFromText;
	private static Text searchDialogAlbumYearToText;
	private static Text searchDialogArtistTitleText;
	private static Text searchDialogSongTitleText;
	private static Text searchDialogSongArtistText;
	private static Text searchDialogSongLyricText;
	private Table albumTable;
	private Table artistTable;
	private Table songTable;
	//	private Table searchAlbumResultsTable;
	//	private Table searchAlbumResultsTable;
	private static final String DELIMITER = "\t";
	private static String[] columnNames = {"Title", "Performer"};
	private static Combo AlbumCombo;
	private static Combo ArtistCombo;
	private static Combo SongCombo;


	static Image background = new Image(display,
			Main.class.getResourceAsStream("search-back.png"));

	Color color = new Color(display, 8, 164, 199);
	private static Table searchTableSongResults;

	public static GuiGetReturnedResults guiInt = new GuiGetReturnedResults();
	public static GuiCallDb dbGui = new GuiCallDb();
	public static DB db ;
	private static User user;
	public static CountDownLatch signal;






	public static void main(String[] args) {

		Main.signal = new CountDownLatch(1);
		Main.dbGui.connectToDataBase();
		try {	
			Main.signal.await();
		} catch (InterruptedException e) {
			MessageBox messageBox = new MessageBox(
					Main.shell, 32);
			messageBox.setText("Error");
			messageBox.setMessage("Error: "
					+ e.getLocalizedMessage());
			messageBox.open();
			e.printStackTrace();
		}
		String guiErrorMsg = Main.guiInt.getMassage();
		System.out.println(guiErrorMsg + "login class");
		if (guiErrorMsg!=null){
			MessageBox messageBox = new MessageBox(
					Main.shell, 32);
			messageBox.setText("Error");
			messageBox.setMessage("Error: "
					+ guiErrorMsg);
			messageBox.open();
		}
		showGUI();
		System.exit(-1);
	}

	public static void showGUI() {
		display = Display.getDefault();
		shell = new Shell(display, 224);
		shell.setText("Music Box");

		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		central_x = (int) dim.getWidth() / 2;
		central_y = (int) dim.getHeight() / 2;
		shell.setLocation(central_x - 500, central_y - 300);

		Image progIcon = new Image(display,
				Main.class.getResourceAsStream("icon.png"));
		shell.setImage(progIcon);

		Main inst = new Main(shell, 0);
		Point size = inst.getSize();
		shell.setLayout(new FillLayout());
		shell.layout();
		if ((size.x == 0) && (size.y == 0)) {
			inst.pack();
			shell.pack();
		} else {
			Rectangle shellBounds = shell.computeTrim(0, 0, size.x, size.y);
			shell.setSize(shellBounds.width, shellBounds.height);
		}
		shell.open();
		createMenuBar();
		while (!shell.isDisposed())
			if (!display.readAndDispatch())
				display.sleep();
	}

	public Main(Composite parent, int style) {
		super(parent, style);
		initGUI();
	}

	private void initGUI() {
		try {
			setLayout(null);
			layout();
			pack();
			setSize(1000, 542);

			login();

			searchDialogGroup = new Group(this, 0);
			searchDialogGroup.setLayout(null);
			searchDialogGroup.setBackgroundImage(background);
			searchDialogGroup.setBounds(0, -8, 1000, 542);

			searchDialogAlbumTitleText = new Text(searchDialogGroup, 2048);
			searchDialogAlbumTitleText.setBounds(140, 337, 135, 22);

			searchDialogAlbumPerformerText = new Text(searchDialogGroup, 2048);
			searchDialogAlbumPerformerText.setBounds(140, 368, 135, 22);

			searchDialogAlbumGenreText = new Text(searchDialogGroup, 2048);
			searchDialogAlbumGenreText.setBounds(140, 399, 135, 22);

			searchDialogAlbumYearFromText = new Text(searchDialogGroup, 2048);
			searchDialogAlbumYearFromText.setBounds(140, 430, 45, 22);

			searchDialogAlbumYearToText = new Text(searchDialogGroup, 2048);
			searchDialogAlbumYearToText.setBounds(229, 430, 45, 22);

			AlbumCombo = new Combo(searchDialogGroup, 8);
			AlbumCombo.setBounds(195, 460, 62, 65);
			String[] items = { "25", "50", "75", "100" };
			AlbumCombo.setItems(items);
			AlbumCombo.select(0);

			ArtistCombo = new Combo(searchDialogGroup, 8);
			ArtistCombo.setBounds(515, 460, 62, 65);
			ArtistCombo.setItems(items);
			ArtistCombo.select(0);

			SongCombo = new Combo(searchDialogGroup, 8);
			SongCombo.setBounds(840, 460, 62, 65);
			SongCombo.setItems(items);
			SongCombo.select(0);

			searchDialogSongTitleText = new Text(searchDialogGroup, 2048);
			searchDialogSongTitleText.setBounds(775, 337, 135, 22);

			searchDialogSongArtistText = new Text(searchDialogGroup, 2048);
			searchDialogSongArtistText.setBounds(775, 368, 135, 22);

			searchDialogSongLyricText = new Text(searchDialogGroup, 2048);
			searchDialogSongLyricText.setBounds(775, 399, 135, 22);

			searchDialogButtonSearchAlbum = new Button(searchDialogGroup,
					16777224);

			searchDialogButtonSearchAlbum.setText("Search");
			searchDialogButtonSearchAlbum.setBackground(this.color);
			searchDialogButtonSearchAlbum.setBounds(110, 488, 150, 30);
			searchDialogButtonSearchAlbum.addListener(13, new Listener() {
				public void handleEvent(Event event) {
					String title = searchDialogAlbumTitleText.getText();
					if (title.equals("")){
						title = null;
					}
					String performer = searchDialogAlbumPerformerText.getText();
					if (performer.equals("")){
						performer = null;
					}
					String genre = searchDialogAlbumGenreText.getText();
					if (genre.equals("")){
						genre = null;
					}
					Boolean isNumeric1 = false;
					Boolean isNumeric2 = false;
					Boolean out = false;
					int years = 0;
					int yearFrom = 0;
					if (isNumeric(searchDialogAlbumYearFromText.getText())){
						if (!searchDialogAlbumYearFromText.getText().equals("")){

							yearFrom = Integer.parseInt(searchDialogAlbumYearFromText.getText());
							if ((yearFrom < 1901) || (yearFrom>2155)){
								out = true;
							}
							years++;
						}
						isNumeric1 = true ;
					}
					int yearTo =  0;
					if (isNumeric(searchDialogAlbumYearToText.getText())){

						if (!searchDialogAlbumYearToText.getText().equals("")){
							yearTo =Integer.parseInt(searchDialogAlbumYearToText.getText());
							if ((yearTo < 1901) || (yearTo>2155)){
								out = true;
							}
							years++;
						}
						isNumeric2 = true;
					}

					int numOfResults = Integer.parseInt(AlbumCombo.getText());

					if ((years == 1)|| (!(isNumeric1&&isNumeric2))||(out)){
						MessageBox messageBox = new MessageBox(
								Main.shell, 32);
						messageBox.setText("Error");
						if  (years == 1){
							messageBox.setMessage("Error: Please enter year from AND year to OR none of them"
									);
						}
						if (!(isNumeric1&&isNumeric2)){
						messageBox.setMessage("Error: Please enter Numeric values for years"
								);
						}
						if (out){
							messageBox.setMessage("Error: Please enter years in the rang 1901-2155"
									);
							}
						messageBox.open();

					}

					else{
						Main.signal = new CountDownLatch(1);
						Main.dbGui.getAdvanceCdSearchResults(title, performer, genre, yearFrom, yearTo, numOfResults);
						try {
							Main.signal.await();
						} catch (InterruptedException e) {
							MessageBox messageBox = new MessageBox(
									Main.shell, 32);
							messageBox.setText("Error");
							messageBox.setMessage("Error: "
									+ e.getLocalizedMessage());
							messageBox.open();
							e.printStackTrace();
						}
						String guiErrorMsg = Main.guiInt.getMassage();
						System.out.println(guiErrorMsg + "login class");
						if (guiErrorMsg!=null){
							MessageBox messageBox = new MessageBox(
									Main.shell, 32);
							messageBox.setText("Error");
							messageBox.setMessage("Error: "
									+ guiErrorMsg);
							messageBox.open();
						}else
							AlbumSearchResultsDialog.openSearchDialog();
					}
				}
			});

			searchDialogArtistTitleText = new Text(searchDialogGroup, 2048);
			searchDialogArtistTitleText.setBounds(440, 337, 135, 22);

			searchDialogButtonSearchArtist = new Button(searchDialogGroup,
					16777224);

			searchDialogButtonSearchArtist.setText("Search");
			searchDialogButtonSearchArtist.setBackground(this.color);
			searchDialogButtonSearchArtist.setBounds(430, 488, 150, 30);
			searchDialogButtonSearchArtist.addListener(13, new Listener() {
				public void handleEvent(Event event) {

					String artist = searchDialogArtistTitleText.getText();
					if (artist.equals("")){
						artist = null;
					}

					int numOfResults = Integer.parseInt(ArtistCombo.getText());

					Main.signal = new CountDownLatch(1);
					Main.dbGui.getArtistSearchResults(artist, numOfResults);
					try {
						Main.signal.await();
					} catch (InterruptedException e) {
						MessageBox messageBox = new MessageBox(
								Main.shell, 32);
						messageBox.setText("Error");
						messageBox.setMessage("Error: "
								+ e.getLocalizedMessage());
						messageBox.open();
						e.printStackTrace();
					}
					String guiErrorMsg = Main.guiInt.getMassage();
					System.out.println(guiErrorMsg + "Main");
					if (guiErrorMsg!=null){
						MessageBox messageBox = new MessageBox(
								Main.shell, 32);
						messageBox.setText("Error");
						messageBox.setMessage("Error: "
								+ guiErrorMsg);
						messageBox.open();
					}else
						ArtistSearchResultsDialog.openSearchDialog();
				}
			});
			searchDialogButtonSearchSong = new Button(searchDialogGroup,
					16777224);

			searchDialogButtonSearchSong = new Button(searchDialogGroup,
					16777224);

			searchDialogButtonSearchSong.setText("Search");
			searchDialogButtonSearchSong.setBackground(this.color);
			searchDialogButtonSearchSong.setBounds(755, 488, 150, 30);
			searchDialogButtonSearchSong.addListener(13, new Listener(){
				public void handleEvent(Event event) {

					String title = searchDialogSongTitleText.getText();
					if (title.equals("")){
						title = null;
					}
					
					
					String artist = searchDialogSongArtistText.getText();
					if (artist.equals("")){
						artist = null;
					}
					
					
					String lyric = searchDialogSongLyricText.getText();
					if (lyric.equals("")){
						lyric = null;
					}

					int numOfResults = Integer.parseInt(SongCombo.getText());

					Main.signal = new CountDownLatch(1);
					Main.dbGui.getAdvanceSongSearchReasults(title, artist, lyric, numOfResults);
					try {
						Main.signal.await();
					} catch (InterruptedException e) {
						MessageBox messageBox = new MessageBox(
								Main.shell, 32);
						messageBox.setText("Error");
						messageBox.setMessage("Error: "
								+ e.getLocalizedMessage());
						messageBox.open();
						e.printStackTrace();
					}
					String guiErrorMsg = Main.guiInt.getMassage();
					System.out.println(guiErrorMsg + "Main");
					if (guiErrorMsg!=null){
						MessageBox messageBox = new MessageBox(
								Main.shell, 32);
						messageBox.setText("Error");
						messageBox.setMessage("Error: "
								+ guiErrorMsg);
						messageBox.open();
					}else
						SongSearchResultsDialog.openSearchDialog();
				}
			});




		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void login() {
		LoginDialog.openLogDialog();
		if (!LoginDialog.successful)
			System.exit(-1);
	}

	private static Menu createMenuBar() {
		Menu menuBar = new Menu(shell, 2);
		shell.setMenuBar(menuBar);

		createAccountMenu(menuBar);
		createEditMenu(menuBar);
		createHelpMenu(menuBar);

		return menuBar;
	}

	private static void createEditMenu(Menu menuBar) {
		MenuItem item = new MenuItem(menuBar, 64);
		item.setText("Edit");
		Menu menu = new Menu(shell, 4);
		item.setMenu(menu);

		menu.addMenuListener(new MenuAdapter() {
			public void menuShown(MenuEvent e) {
			}
		});
		MenuItem subItem = new MenuItem(menu, 0);

		subItem.setText("Import");
		subItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				importDialog.openLogDialog();
			}
		});
		subItem = new MenuItem(menu, 0);
		subItem.setText("Add New Album");
		subItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				AddAlbumDialog.openLogDialog();

			}
		});
		//		subItem = new MenuItem(menu, 0);
		//		subItem.setText("Edit Current Album");
		//		subItem.setEnabled(user.getUserName().equals("admin"));
		//		subItem.addSelectionListener(new SelectionAdapter() {
		//			public void widgetSelected(SelectionEvent e) {
		//				EditAlbumDialog.openLogDialog();
		//
		//			}
		//		});
		//		subItem = new MenuItem(menu, 0);
		//		subItem.setText("Delete Current Album");
		//		subItem.setEnabled(user.getUserName().equals("admin"));
		//		subItem.addSelectionListener(new SelectionAdapter() {
		//			public void widgetSelected(SelectionEvent e) {
		//				//EditAlbumDialog.openLogDialog();
		//
		//			}
		//		});
	}

	private static void createAccountMenu(Menu menuBar) {
		MenuItem item = new MenuItem(menuBar, 64);
		item.setText("My Account");
		Menu menu = new Menu(shell, 4);
		item.setMenu(menu);

		MenuItem subItem = new MenuItem(menu, 0);
		subItem.setText("Change Password");
		subItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				ChangePassDialog.openLogDialog();
			}
		});
		subItem = new MenuItem(menu, 0);
		subItem.setText("Delete Account");
		subItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				DeleteAccountDialog.openLogDialog();
				if (DeleteAccountDialog.successful) {
					Main.shell.close();
					Main.showGUI();
				}
			}
		});
		subItem = new MenuItem(menu, 0);
		subItem.setText("Log Out");
		subItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				Main.shell.close();
				LoginDialog.successful = false;
				Main.showGUI();
			}
		});
		new MenuItem(menu, 2);

		subItem = new MenuItem(menu, 0);
		subItem.setText("Exit");
		subItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				Main.shell.close();
			}
		});
	}

	private static void createHelpMenu(Menu menuBar) {
		MenuItem item = new MenuItem(menuBar, 64);
		item.setText("Help");
		Menu menu = new Menu(shell, 4);
		item.setMenu(menu);

		MenuItem subItem = new MenuItem(menu, 0);
		subItem.setText("About");
		subItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				MessageBox box = new MessageBox(Main.shell, 0);
				box.setText(Main.shell.getText());
				box.setMessage(Main.shell.getText());
				box.open();
			}
		});
	}

	private static void newEntry() {
		DataEntryDialog dialog = new DataEntryDialog(shell);
		dialog.setLabels(columnNames);
		String[] data = dialog.open();
		if (data != null) {
			TableItem item = new TableItem(searchTableSongResults, 0);
			item.setText(data);
		}
	}

	private static void editEntry(TableItem item) {
		DataEntryDialog dialog = new DataEntryDialog(shell);
		dialog.setLabels(columnNames);
		String[] values = new String[searchTableSongResults.getColumnCount()];
		for (int i = 0; i < values.length; i++) {
			values[i] = item.getText(i);
		}
		dialog.setValues(values);
		values = dialog.open();
		if (values != null)
			item.setText(values);
	}

	public static int getCentral_x() {
		return central_x;
	}

	public static void setCentral_x(int centralX) {
		central_x = centralX;
	}

	public static int getCentral_y() {
		return central_y;
	}

	public static void setCentral_y(int centralY) {
		central_y = centralY;
	}

	public static User getUser() {
		return user;
	}

	public static void setUser(User user) {
		Main.user = user;

	}
	private boolean isNumeric(String str)
	{
		NumberFormat formatter = NumberFormat.getInstance();
		ParsePosition pos = new ParsePosition(0);
		formatter.parseObject(str, pos);
		return str.length()==pos.getIndex();
	}
}